class Solution(object):
    def arrayNesting(self, nums):
        n = len(nums)
        used = [0] * n
        p = [0] * n

        def dfs(index):
            if used[index] == 1:
                return p[index]
            else:
                used[index] = 1
                p[index] = 1 + dfs(nums[index])
                return p[index]

        for i in range(n):
            dfs(i)
        return max(p)


data = Solution()
nums = [5, 4, 0, 3, 1, 6, 2]
print(data.arrayNesting(nums))
nums = [0, 2, 3, 4, 1, 6, 5]
print(data.arrayNesting(nums))